package api

import (
	"api/global"
	"api/internal/model"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
)

func OrderPayCallback(c *gin.Context) {

	err := c.Request.ParseForm()
	if err != nil {
		return
	}
	fmt.Println(c.Request.PostForm)

	status := c.Request.PostForm.Get("trade_status")
	if status != "TRADE_SUCCESS" {
		c.JSON(http.StatusBadRequest, gin.H{
			"Message": "支付失败",
			"Data":    nil,
			"Code":    500,
		})
		return
	}

	OrderSn := c.Request.PostForm.Get("out_trade_no")
	if OrderSn == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"Message": "支付订单不存在",
			"Data":    nil,
			"Code":    500,
		})
		return
	}

	userOrderKey := fmt.Sprintf("orderSn:%s", OrderSn)

	// 清除Redis订单
	err = global.Rdb.Del(context.Background(), userOrderKey).Err()
	if err != nil {
		return
	}

	var dbOrder model.Order
	if err := global.DB.Where("order_sn = ?", OrderSn).First(&dbOrder).Error; err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "订单不存在"})
		return
	}

	err = global.DB.Model(&dbOrder).Where("order_sn = ?", OrderSn).Update("number", gorm.Expr("number - 1")).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"Message": "数据库库存扣减失败",
			"Data":    nil,
			"Code":    500,
		})
		return
	}

	// 修改订单状态  已支付状态
	err = global.DB.Model(model.Order{}).Where("order_sn = ?", OrderSn).Update("order_status", 2).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"Message": "订单支付状态修改失败",
			"Data":    nil,
			"Code":    500,
		})
		return
	}
}
